package com.shangrila.web.taobao.activity;

import java.util.HashSet;
import java.util.Set;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringEscapeUtils;
import org.apache.commons.lang.StringUtils;
import org.htmlparser.Node;
import org.htmlparser.NodeFilter;
import org.htmlparser.Parser;
import org.htmlparser.tags.LinkTag;
import org.htmlparser.util.NodeList;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;

import com.opensymphony.xwork2.ActionSupport;
@Controller
public class Discount extends ActionSupport {

	private static final long serialVersionUID = -2575855342218355366L;
	private String url = "http://youhuiquan.tmall.com/";
	private String info;
	private final static Logger log = LoggerFactory.getLogger(Discount.class);
	private Set<String> discountUrls = new HashSet<String>();
	
	@Override
	public String execute() throws Exception {
		if(StringUtils.isBlank(url)){
			info = "请输入正确的淘宝活动页面，如：http://youhuiquan.tmall.com/";
			discountUrls  = new HashSet<String>();
			return SUCCESS;
		}
		try {
			Document doc = Jsoup.connect(url).ignoreHttpErrors(true).timeout(2000).get();
			// 使用后HTML Parser 控件
			Parser myParser = Parser.createParser(StringEscapeUtils.unescapeHtml(doc.html()), "utf-8");
			// 通过过滤器过滤出<A>标签
			NodeList nodeList = myParser.extractAllNodesThatMatch(new NodeFilter() {
				private static final long serialVersionUID = 1L;
						// 实现该方法,用以过滤标签
						public boolean accept(Node node) {
							if (node instanceof LinkTag) // <A>标记
								return true;
							return false;
						}
					});
			// 打印
			for (int i = 0; i < nodeList.size(); i++) {
				LinkTag n = (LinkTag) nodeList.elementAt(i);
				String link = n.extractLink();
				if (link != null && link.indexOf("http://ecrm.taobao.com/shopbonusapply/buyer_apply.htm") == 0) {
					discountUrls.add(link);
				}
			}
			if(CollectionUtils.isNotEmpty(discountUrls)){
				info = "领取成功，一共领取了"+discountUrls.size()+"张优惠劵(未成功者，请登录后重试)。查看地址:<a target='_blank' href='http://ecrm.taobao.com/mallcoupon/got_bonus.htm'>http://ecrm.taobao.com/mallcoupon/got_bonus.htm</a>";
			}else{
				info = "根据你提供的地址，竟然没找到要领取的优惠劵，你登录淘宝了吗？输入了正确的地址了吗？";
				discountUrls = new HashSet<String>();
			}
		} catch (Exception e) {
			info = "操作出错，请稍后再试";
			discountUrls = new HashSet<String>();
			log.error("Catch a exception.",e);
		}
		return SUCCESS;
	}

	public String getInfo() {
		return info;
	}

	public Set<String> getDiscountUrls() {
		return discountUrls;
	}

	public void setUrl(String url) {
		this.url = url;
	}
}
